package com.gxa.autoparts.portal.service.impl;

import com.gxa.autoparts.core.common.ExceptionCode;
import com.gxa.autoparts.core.exception.BusinessException;
import com.gxa.autoparts.core.pojo.DoorImg;
import com.gxa.autoparts.core.pojo.UserVipVo;
import com.gxa.autoparts.core.pojo.Vip;
import com.gxa.autoparts.core.service.impl.BaseServiceImpl;
import com.gxa.autoparts.portal.mapper.DoorImgMapper;
import com.gxa.autoparts.portal.mapper.VipMapper;
import com.gxa.autoparts.portal.service.UserVipService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service("userVipService")
@Transactional(rollbackFor = Throwable.class)
public class UserVipServiceImpl extends BaseServiceImpl<Vip> implements UserVipService {

    @Autowired
    private DoorImgMapper doorImgMapper=null;


    @Autowired
    private VipMapper vipMapper=null;

    @Override
    public void applyVip(UserVipVo userVipVo) throws BusinessException {
        Vip vip = userVipVo.getVip();
        Example example=new Example(Vip.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("userId",vip.getVipId());

        List<Vip> vips = vipMapper.selectByExample(example);
        //数据可中无数据或者审核为通过
        if(vips.size()<1||vips.get(0).getState().equals(2)){
            //删除原有数据
            vipMapper.deleteByExample(example);
            List<DoorImg> list = userVipVo.getList();
            vipMapper.insertSelective(vip);
            for (DoorImg d  : list) {
                d.setVipId(vip.getVipId());
                doorImgMapper.insertSelective(d);
            }

        }else {
            throw new BusinessException(ExceptionCode.IS_EXIST);
        }


    }

    @Override
    public UserVipVo vipDetail(Long userId) throws BusinessException {
        UserVipVo userVipVo=new UserVipVo();
        Example example=new Example(Vip.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("userId",userId);

        List<Vip> vips = vipMapper.selectByExample(example);
        Vip vip = vips.get(0);
        System.out.println(vip);
        if(vip==null){
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
        Example example1=new Example(Vip.class);
        Example.Criteria criteria1 = example1.createCriteria();

        criteria1.andEqualTo("vipId",vip.getVipId());

        List<DoorImg> doorImgs = doorImgMapper.selectByExample(example1);

        userVipVo.setVip(vip);
        userVipVo.setList(doorImgs);
        return userVipVo;
    }
}
